package com.taoist_awei.blog.infrastructure.service;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.taoist_awei.blog.core.ArticleService;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;


@Service
public class DefaultArticleService implements ArticleService {

    @Override
    public String getSummary(String content) {
        Pattern pattern = Pattern.compile("#+\\s[\\u4e00-\\u9fa5A-Za-z0-9]+");
        String[] strings = pattern.split(content, 0);
        String paragraph1;
        if (strings == null || strings.length == 0) {
            return "";
        }
        if (strings.length > 1) {
            paragraph1 = strings[1].trim();
        } else {
            paragraph1 = strings[0].trim();
        }
        StringBuilder builder = new StringBuilder(paragraph1);
        if (builder.length() < 50) {
            return builder.toString();
        } else {
            CharSequence charSequence = builder.subSequence(0, 50);
            StringBuilder builder1 = new StringBuilder(charSequence.toString());
            builder1.append("...");
            return builder1.toString();
        }
    }

    @Override
    public Integer getReadTime(String content) {
        int len = content.length();
        int num = 0;
        for (int i = 0; i < len; ++i) {
            char c = content.charAt(i);
            if (Character.isLetterOrDigit(c) && String.valueOf(c).matches("[\u4e00-\u9fa5]")) {
                num++;
            }
        }
        int minute = num / 300;
        return minute + 1;
    }

    @Override
    public Integer getWords(String content) {
        int res = 0;
        for (int i = 0; i < content.length(); ++i) {
            char c = content.charAt(i);
            if (Character.isWhitespace(c)) {
                continue;
            }
            res++;
        }
        return res;
    }
}
